#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
#include "Input.h"
#include "Renderer.h"
#include "Game.h"

int main(int argc, char **argv)
{
	// Init
	al_init();
	al_init_primitives_addon();
	al_install_mouse();
	al_install_keyboard();
	al_install_joystick();
	al_reconfigure_joysticks();

	// Core
	Input input;
	Renderer renderer;
	Game game(&renderer);

	// Event queue
	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	al_register_event_source(event_queue, al_get_display_event_source(renderer.GetDisplay()));
	al_register_event_source(event_queue, al_get_timer_event_source(game.GetTimer()));
	al_register_event_source(event_queue, al_get_mouse_event_source());
	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_joystick_event_source());
	  
	// Main event loop
	bool redraw = true;
	bool exit = false;
	while(!exit)
	{
    ALLEGRO_EVENT ev; 
    al_wait_for_event(event_queue, &ev);

		input.ProceedEvent(ev);

    if(ev.type == ALLEGRO_EVENT_TIMER)
		{
			game.ProceedInput(&input);

			redraw = true;

			if(game.IsDynamic()) game.Tick();
			input.Tick();

			if(game.exitFlag) break;
    }
    else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			break;
    }
		else if(ev.type == ALLEGRO_EVENT_DISPLAY_RESIZE)
		{
			int sw = ev.display.width;
			int sh = ev.display.height;

			renderer.ResizeWindow(sw,sh);
			redraw = true;
    }

    if(redraw && al_is_event_queue_empty(event_queue))
		{
      redraw = false;
			if(!game.IsDynamic()) game.Tick();
			renderer.Draw();

			static int64_t timerStart = 0;
			if(al_get_timer_count(game.GetTimer()) - timerStart >= Game::tps)
			{
				Game::fps = Game::ticks;
				Game::ticks = 0;
				timerStart = al_get_timer_count(game.GetTimer());
			}
			Game::ticks++;
    }
  }

  al_destroy_event_queue(event_queue);

  return 0;
}